<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Entity\Category;
use AppBundle\Entity\BlogPost;
use AppBundle\Form\BlogPostType;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
class BlogPostController extends Controller{

    /**
    * @Route("admin/blog/{id}/create",name="admin_blog_create")
    * @ParamConverter("category",class="AppBundle:Category")
    */
    public function newAction(Request $request,Category $category){
      $post = new BlogPost();
      $form = $this->createForm(BlogPostType::class, $post);

      $form->handleRequest($request);

      if($form->isSubmitted() && $form->isValid()){

        $em = $this->getDoctrine()->getManager();
        $post->setCategory($category);
        $em->persist($post);
        $em->flush();

        return $this->redirect($this->generateUrl('admin_blog_list'));
      }

      return $this->render('admin/blog/create.html.twig',array(
        'form' => $form->createView(),
      ));
    }

    /**
    * @Route("admin/blog/list",name="admin_blog_list")
    */
    public function listAction(){
      $posts = $this->getDoctrine()
          ->getRepository("AppBundle:BlogPost")
          ->findLastest();

      return $this->render('admin/blog/list.html.twig',array(
        'posts' => $posts,
      ));
    }
}
